package com.dd.cloud.user.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dd.cloud.common.config.common.ProfilesProperties;
import com.dd.cloud.common.constants.HealthConstants;
import com.dd.cloud.common.constants.RedisKeyConstants;
import com.dd.cloud.common.constants.SmsConstants;
import com.dd.cloud.user.config.ZerkProperties;
import com.dd.cloud.user.mq.MQConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class AIInterfaceTask {
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ZerkProperties zerkProperties;
    @Autowired
    private ProfilesProperties profilesProperties;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 10分钟测试一次智尔康的服务是否正常
     */
    @Scheduled(cron = "0 */10 * * * ?")
    public void taskShareOrder() {
        //只有正式服才监控
        if (!profilesProperties.getActive().equals(HealthConstants.ProfilesType.PROD)){
            return;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("xuhao", "ZK_FUB");
        jsonObject.put("ids", "A5,B5,B7,C2,C4");
        jsonObject.put("BLH", System.currentTimeMillis());
        jsonObject.put("NL", "28");
        jsonObject.put("XB", "男");
        jsonObject.put("ZB", "汉族");
        jsonObject.put("HYZK", "已婚");
        jsonObject.put("XM", "张三");
        jsonObject.put("SecretKey", zerkProperties.getZerkSecretKey());
        jsonObject.put("flag", "1");
        String paramsStr = jsonObject.toJSONString();
        log.info("定时器在线诊断接口参数:{}", paramsStr);
        HttpHeaders headers = new HttpHeaders();
        // 定义请求参数类型，这里用json所以是MediaType.APPLICATION_JSON_UTF8，不是UTF-8将会返回-2008错误码
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<>(paramsStr, headers);
        String doctorResultVo = "";
        try {
            doctorResultVo = restTemplate.postForObject(zerkProperties.getAskDoctorsUrl(), entity, String.class);
        } catch (Exception e) {
            log.info("定时器在线诊断接口请求异常:{}", doctorResultVo);
            sendMsg();
        }
        if ("".equals(doctorResultVo)) {
            return;
        }
        JSONObject jsonObj = JSON.parseObject(doctorResultVo);
        // 解析请求状态码，0为正常，其他为异常sErrorMsg为异常信息
        int nErrorCode = jsonObj.getInteger("nErrorCode");
        if (nErrorCode != 0) {
            log.info("定时器在线诊断接口异常结果:{}", doctorResultVo);
            sendMsg();
        }
    }

    /**
     * 发送短信, 连续3次异常, 发送短信, 短信每天只发2次, 以免长时间异常短信轰炸
     */

    private void sendMsg(){
        Long increment = redisTemplate.boundValueOps(RedisKeyConstants.ZRK_ERROR).increment();
        redisTemplate.expire(RedisKeyConstants.ZRK_ERROR, 1, TimeUnit.DAYS);
        if (increment > 6){
            return ;
        }
        if (increment % 3 == 0){
            String[] phs = new String[]{"13554917160", "18079640577", "19974324119"};
            for (String phone : phs) {
                Map<String, String> msg = new HashMap<>();
                msg.put("phone", phone);
                msg.put("param_type", SmsConstants.ParamType.JSON);
                msg.put("sms_template", SmsConstants.Template.ZRK_INTERFACE_ERROR);
                amqpTemplate.convertAndSend(MQConfig.SMS_EXCHANGE, MQConfig.SMS_KEY, msg);
            }
        }
    }
}
